<?php
/**
 * 处理程序
 *
 * @author 老虎
 * @url http://bbs.we7.cc/
 */
defined('IN_IA') or exit('Access Denied');

class nbs_scdyModuleProcessor extends WeModuleProcessor {
	public function respond() {
        global $_W;
        load()->model('mc');  
        $poster=pdo_fetch ( 'select * from ' . tablename ($this->modulename . "_poster" ) . " where weid='{$_W['uniacid']}' limit 1" );      

		$fans = mc_fetch($this->message['from']);
         //file_put_contents(IA_ROOT."/addons/nbs_scdy/log.txt","\n old:".json_encode($this->message),FILE_APPEND);
         if (empty($fans['nickname']) || empty($fans['avatar'])){
                    $openid = $this->message['from'];
					$ACCESS_TOKEN = $this->getAccessToken();
					$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$ACCESS_TOKEN}&openid={$openid}&lang=zh_CN";
					load()->func('communication');
					$json = ihttp_get($url);
					$userInfo = @json_decode($json['content'], true);
					$fans['nickname'] = $userInfo['nickname'];
					$fans['avatar'] = $userInfo['headimgurl'];
					$fans['province'] = $userInfo['province'];
					$fans['city'] = $userInfo['city'];
                    $fans['unionid'] = $userInfo['unionid'];                    
				}
        //file_put_contents(IA_ROOT."/addons/nbs_scdy/log.txt","\n old:".json_encode($poster),FILE_APPEND);

        if(!empty($poster)){
           if($poster['starttime']>time()){
              return $this->postText($this->message['from'],$poster['nostarttips']);              
           }elseif($poster['endtime']<time()){
              return $this->postText($this->message['from'],$poster['endtips']);
           }           
         } //活动结束时间

         //生成海报开始
          if($this->message['msgtype'] == 'text' || $this->message['event'] == 'CLICK'){

              $gzmember=pdo_fetch("SELECT * FROM " . tablename($this->modulename."_member") . " WHERE weid = '{$_W['uniacid']}' and from_user = '{$this->message['from']}'");//当前粉丝信息
              if(empty($gzmember['fans_type'])){
                  $this->postText($this->message['from'],'对不起您还不是会员，暂时不能生成自己的专属海报');
                  exit;
              }   
             
             if($poster['winfo1']){
                $info=str_replace('#时间#',date('Y-m-d H:i',time()+30*24*3600),$poster['winfo1']);
                $this->postText($this->message['from'],$info);
             }
             if ($poster['winfo2']){
                $msg2 = $poster['winfo2'];
                $this->postText($this->message['from'],$msg2);
                
             }
             $img = $this->createPoster($fans,$poster,$this->message['from']);
             //file_put_contents(IA_ROOT."/addons/nbs_scdy/log.txt","\n old:".json_encode($img),FILE_APPEND);
             $media_id = $this->uploadImage($img); 
             if ($this->message['checked'] == 'checked'){
                 $this->sendImage($this->message['from'],$media_id);
                 return '';
             }else return $this->respImage($media_id);
             exit;
         }
        //生成海报结束

        //file_put_contents(IA_ROOT."/addons/nbs_dingyue/log.txt","\n old:".json_encode($this->message),FILE_APPEND);

        //关注扫码奖励
         if ($this->message['msgtype'] == 'event') {
            $poster=pdo_fetch ( 'select * from ' . tablename ($this->modulename . "_poster" ) . " where weid='{$_W['uniacid']}' limit 1" );
            $cfg=$this->module['config'];
            $scene_id=str_replace('qrscene_','',$this->message['eventkey']);//扫码关注场景ID
            
            if ($this->message['event'] == 'subscribe') {  
              $this->reward($scene_id,$this->message['from'],$cfg,$fans,$poster);
              
              return $this->PostNews($poster,$fans['nickname']);//关注推送图文
            }            
         }
         //关注扫码奖励结束

         //重复扫码提醒
         if ($this->message['event'] == 'SCAN') {
                $cfg=$this->module['config'];
                $msg1=str_replace('#昵称#',$fans['nickname'], $cfg['cfinfo']);
                $msg1=str_replace('#gzname#',$_W['account']['name'], $msg1);  

                //已关注会员开始
                $member=pdo_fetch("SELECT * FROM ".tablename($this->modulename . "_member")." WHERE weid = :weid and from_user=:from_user", array(':weid' => $_W['uniacid'],':from_user'=>$this->message['from']));//当前用户信息
                 if(empty($member)){
                     if($member['helpid']!==null){
                       if($member['helpid']==0){
                         $this->postText($this->message['from'],$msg1);
                         exit;
                       }
                     }
                     $scene_id=str_replace('qrscene_','',$this->message['eventkey']);//扫码关注场景ID
                     $this->reward($scene_id,$this->message['from'],$cfg,$fans,$poster);
                      Return '';
                      exit;                   
                 }

             return  $this->postText($this->message['from'],$msg1);
            }
       //重复扫码结束


	}


    public function reward($scene_id,$openid,$cfg,$fans,$poster){
        global $_W;  
        $cfg = $this->module['config'];
        $hmember=pdo_fetch("SELECT * FROM ".tablename($this->modulename."_member")." WHERE weid = :weid and sceneid=:sceneid", array(':weid' => $_W['uniacid'],':sceneid'=>$scene_id));//事件所有者
        $member=pdo_fetch("SELECT * FROM ".tablename($this->modulename."_member")." WHERE weid = :weid and from_user=:from_user", array(':weid' => $_W['uniacid'],':from_user'=>$openid));//当前用户信息
        //file_put_contents(IA_ROOT."/addons/nbs_youzan/log.txt","\n old:".json_encode($member),FILE_APPEND);
        if (empty($member)){//如果粉丝不存在插入数据奖励
            pdo_insert($this->modulename."_member",
                    array(
                        'weid' => $_W['uniacid'], 
                        'uid'=>$fans['uid'],
                        'from_user' => $openid, 
                        'unionid' => $fans['unionid'], 
                        'nickname' => $fans['nickname'], 
                        'helpid'=>$hmember['id'],
                        'avatar' => $fans['avatar'], 
                        'sex' => $fans['sex'], 
                        'follow'=>1,
                        'province' => $fans['province'], 
                        'city' => $fans['city'], 
                        'time' => TIMESTAMP,
                        'createtime'=>TIMESTAMP
                    ));
            $share['id'] = pdo_insertid();
            $share = pdo_fetch('select * from '.tablename($this->modulename."_member")." where id='{$share['id']}'");


            //粉丝扫码关注提醒 
            $rwurl=$_W['siteroot'].str_replace('./','app/',$this->createMobileurl('jiameng'));
            $rwmsg=array(
                        'first' => array(
                            'value' => "会员昵称：".$fans['nickname'],
                            "color" => "#ff0000"
                        ),
                        'keyword1' => array(
                            'value' =>$share['id'],
                            "color" => "#4a5077"
                        ),
                        'keyword2' => array(
                            'value' => date('Y-m-d H:i:s',time()),
                        ),
                        'remark' => array(
                            'value' => $cfg['info0'],
                            "color" => "#008920"
                        )
                    );
            $this->sendMsg($this->message['from'],$cfg['mb1'], $rwmsg,$cfg['info0'],$rwurl);
          //粉丝扫码关注提醒 结束

                  if($hmember['status']<>1){                     
                      //一级提醒 
                        $rwurl=$_W['siteroot'].str_replace('./','app/',$this->createMobileurl('jiameng'));
                        $rwmsg=array(
                                    'first' => array(
                                        'value' => "会员昵称：".$fans['nickname'],
                                        "color" => "#ff0000"
                                    ),
                                    'keyword1' => array(
                                        'value' =>$share['id'],
                                        "color" => "#4a5077"
                                    ),
                                    'keyword2' => array(
                                        'value' => date('Y-m-d H:i:s',time()),
                                    ),
                                    'remark' => array(
                                        'value' => $cfg['info1'],
                                        "color" => "#008920"
                                    )
                                );
                        $this->sendMsg($hmember['from_user'],$cfg['mb1'], $rwmsg,$cfg['info1'],$rwurl);
                      //一级提醒 结束
                  }
                  

                  if(empty($hmember['helpid'])){
                    return '';
                  }
                  $fmember=pdo_fetch("SELECT * FROM ".tablename($this->modulename."_member")." WHERE weid = :weid and id=:id", array(':weid' => $_W['uniacid'],':id'=>$hmember['helpid']));
                  if($fmember['status']==1 || empty($fmember)){
                        return '';
                   }
                      //二级提醒 
                        $rwurl=$_W['siteroot'].str_replace('./','app/',$this->createMobileurl('jiameng'));
                        $rwmsg=array(
                                    'first' => array(
                                        'value' => "会员昵称：".$fans['nickname'],
                                        "color" => "#ff0000"
                                    ),
                                    'keyword1' => array(
                                        'value' =>$share['id'],
                                        "color" => "#4a5077"
                                    ),
                                    'keyword2' => array(
                                        'value' => date('Y-m-d H:i:s',time()),
                                    ),
                                    'remark' => array(
                                        'value' => $cfg['info2'],
                                        "color" => "#008920"
                                    )
                                );
                        $this->sendMsg($fmember['from_user'],$cfg['mb1'], $rwmsg,$cfg['info2'],$rwurl);
                      //二级提醒 结束

                  //三级奖励
                      if(empty($fmember['helpid'])){
                        return '';
                      }
                      $gmember=pdo_fetch("SELECT * FROM ".tablename('nbs_youzan_share')." WHERE weid = :weid and openid=:openid", array(':weid' => $_W['uniacid'],':openid'=>$fmember['helpid']));
                      if($gmember['status']==1 || empty($gmember)){
                            return '';
                          }
                        //三级提醒 
                        $rwurl=$_W['siteroot'].str_replace('./','app/',$this->createMobileurl('jiameng'));
                        $rwmsg=array(
                                    'first' => array(
                                        'value' => "会员昵称：".$fans['nickname'],
                                        "color" => "#ff0000"
                                    ),
                                    'keyword1' => array(
                                        'value' =>$share['id'],
                                        "color" => "#4a5077"
                                    ),
                                    'keyword2' => array(
                                        'value' => date('Y-m-d H:i:s',time()),
                                    ),
                                    'remark' => array(
                                        'value' => $cfg['info3'],
                                        "color" => "#008920"
                                    )
                                );
                        $this->sendMsg($gmember['from_user'],$cfg['mb1'], $rwmsg,$cfg['info3'],$rwurl);
                      //三级提醒 结束
         
        }

        if ($poster['gztype'] == 1){
            if($poster['winfo1']){
                $info=str_replace('#时间#',date('Y-m-d H:i',time()+30*24*3600),$poster['winfo1']);
                $this->postText($this->message['from'],$info);
             }
             if ($poster['winfo2']){
                $msg2 = $poster['winfo2'];
                $this->postText($this->message['from'],$msg2);
             }
            $img = $this->createPoster($fans,$poster,$this->message['from']);
            $media_id = $this->uploadImage($img); 
            $this->sendImage($this->message['from'],$media_id);
        }
    }


     /**
	 * @name 	单发模式
	 * @param 	openid 		粉丝编号
	 * @param 	tplmsgid	模版消息id
	 * @param 	data 		数据包
     * @param 	data1 		客服消息信息
	 * @param 	url 		跳转地址
	 */
	public function sendMsg($openid, $tplmsgid, $data = array(),$data1,$url ="") {
		global $_W;
        $cfg = $this->module['config'];
		if (!empty($data)) {
			//记录存在 | 发送接口
			$account = WeAccount::create($_W['account']['acid']);
			//公号类型
			if (empty($cfg['mb1'])) {
				//订阅号 | 客服消息
				$this->postText($this->message['from'],$data1);
			} elseif ($_W['account']['level'] == 4) {
				//服务号 | 模板消息
                return $account->sendTplNotice($openid, $tplmsgid, $data, $url);
			}
		}
	}


    public function getnews() {//单图文推送        
        $news=array('title'=>'新会员加入提醒','description'=>'会员：小胡\r\n时间：2016','url'=>'asfadf','picurl'=>'');
        $this->sendNews($news,$this->message['from']);//图文
    }

    public function sendNews($news,$openid) {
        /*$custom = array(
                'touser' => $openid,
				'msgtype' => 'news',
				'news' => array(
                              'articles'=>array(
                                              array(
                                               'title' => '测试标题',
                                               'description' => '内容测试',
                                               'url' => 'http://www.baidu.com',
                                               'picurl' => 'http://cs.wzapi.com/attachment/headimg_2.jpg',
                                              )
                                          )
                               ),
				
			);
        $result =urldecode(json_encode($custom));*/
        $result='{"touser":"'.$openid.'","msgtype":"news","news":{"articles":[{"title":"'.$news['title'].'","description":"'.$news['description'].'","url":"'.$news['url'].'","picurl":"'.$news['picurl'].'"}]}}';
        $access_token=$this->getAccessToken();
		$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$access_token}";
        $ret = ihttp_request($url, $result);
		return $ret;
	}


    private $sceneid = 0;
	private $Qrcode = "/addons/nbs_scdy/qrcode/mposter#sid#.jpg";
	private function createPoster($fans,$poster,$openid){
		global $_W;
		$bg = $poster['bg'];
		$share = pdo_fetch('select * from '.tablename($this->modulename."_member")." where weid='{$_W['uniacid']}' and from_user='{$openid}' limit 1");
        
		if (empty($share)){
			pdo_insert($this->modulename."_member",
					array(
							'uid'=>$fans['uid'],
							'nickname'=>$fans['nickname'],
							'avatar'=>$fans['avatar'],
							'createtime'=>TIMESTAMP,
							'helpid'=>0,
							'weid'=>$_W['uniacid'],
                            'from_user'=>$this->message['from'],
                            'unionid'=>$fans['unionid'],
                            'follow'=>1
					));
			$share['id'] = pdo_insertid();
			$share = pdo_fetch('select * from '.tablename($this->modulename."_member")." where id='{$share['id']}'");
		}else pdo_update($this->modulename."_member",array('updatetime'=>time()),array('id'=>$share['id']));


		$qrcode = str_replace('#sid#',$share['id'],IA_ROOT .$this->Qrcode);
		$data = json_decode(str_replace('&quot;', "'", $poster['data']), true);
		include 'func.php';
		set_time_limit(0);
		@ini_set('memory_limit', '256M');
		$size = getimagesize(tomedia($bg));
		$target = imagecreatetruecolor($size[0], $size[1]);
		$bg = imagecreates(tomedia($bg));
		imagecopy($target, $bg, 0, 0, 0, 0,$size[0], $size[1]);
		imagedestroy($bg);

        
		
		foreach ($data as $value) {
			$value = trimPx($value);
			if ($value['type'] == 'qr'){
                $url = $this->getQR($fans,$poster,$share['id']);   
                //file_put_contents(IA_ROOT."/addons/nbs_scdy/log.txt","\n old:".json_encode($url),FILE_APPEND);
				if (!empty($url)){
					$img = IA_ROOT ."/temp_qrcode.png";
					include "phpqrcode.php";
					$errorCorrectionLevel = "L";
					$matrixPointSize = "4";
					QRcode::png($url, $img, $errorCorrectionLevel, $matrixPointSize,2);
					mergeImage($target,$img,array('left'=>$value['left'],'top'=>$value['top'],'width'=>$value['width'],'height'=>$value['height']));
					@unlink($img);
				}
			}elseif ($value['type'] == 'img'){
				$img = saveImage($fans['avatar']);
				mergeImage($target,$img,array('left'=>$value['left'],'top'=>$value['top'],'width'=>$value['width'],'height'=>$value['height']));
				@unlink($img);
			}elseif ($value['type'] == 'name') mergeText($this->modulename,$target,$fans['nickname'],array('size'=>$value['size'],'color'=>$value['color'],'left'=>$value['left'],'top'=>$value['top']),$poster);
		}
		imagejpeg($target, $qrcode);
		imagedestroy($target);
		return $qrcode;
	}

    private function getQR($fans,$poster,$sid){        
		global $_W;
		$pid = $poster['id'];
        
        //file_put_contents(IA_ROOT."/addons/nbs_scdy/log.txt","\n old:".json_encode($this->rule),FILE_APPEND);
       // file_put_contents(IA_ROOT."/addons/nbs_scdy/log.txt","\n old:".json_encode($this->sceneid),FILE_APPEND);
		if (empty($this->sceneid)){
           
			$share = pdo_fetch('select * from '.tablename($this->modulename."_member")." where id='{$sid}'");
            
			if (!empty($share['url'])){
				$out = false;  
				if ($poster['rtype']){
					$qrcode = pdo_fetch('select * from '.tablename('qrcode')
						." where uniacid='{$_W['uniacid']}' and qrcid='{$share['sceneid']}' "
						." and name='".$this->modulename."' and ticket='{$share['ticketid']}' and url='{$share['url']}'");
					if($qrcode['createtime'] + $qrcode['expire'] < time()){
						pdo_delete('qrcode',array('id'=>$qrcode['id']));
						$out = true;
					}
				}
				if (!$out){
					$this->sceneid = $share['sceneid'];
					return $share['url'];
				}
			}

            
			
			$this->sceneid = pdo_fetchcolumn('select sceneid from '.tablename($this->modulename."_member")." where weid='{$_W['uniacid']}' order by sceneid desc limit 1");
			if (empty($this->sceneid)) $this->sceneid = 50000001;
			else $this->sceneid++;
			$barcode['action_info']['scene']['scene_id'] = $this->sceneid;
			
			load()->model('account');
			$acid = pdo_fetchcolumn('select acid from '.tablename('account')." where uniacid={$_W['uniacid']}");
			$uniacccount = WeAccount::create($acid);
			$time = 0;
			if ($poster['rtype']){
				$barcode['action_name'] = 'QR_SCENE';
				$barcode['expire_seconds'] = 30*24*3600;
				$res = $uniacccount->barCodeCreateDisposable($barcode);
				$time = $barcode['expire_seconds'];
			}else{
				$barcode['action_name'] = 'QR_LIMIT_SCENE';
				$res = $uniacccount->barCodeCreateFixed($barcode);
			}
            //$rid = $this->rule;
            $rid=$poster['rid'];
            $sql = "SELECT * FROM " . tablename('rule_keyword') . " WHERE `rid`=:rid LIMIT 1";
            $row = pdo_fetch($sql, array(':rid' => $rid));
			
			pdo_insert('qrcode',
							array('uniacid'=>$_W['uniacid'],
                            'acid'=>$acid,
                            'qrcid'=>$this->sceneid,
                            'name'=>$this->modulename,
                            'keyword'=>$row['content'],
                            'model'=>1,
                            'ticket'=>$res['ticket'],
                            'expire'=>$time,
                            'createtime'=>time(),
                            'status'=>1,
                            'url'=>$res['url']
							)
			);
			
			pdo_update($this->modulename."_member",array('sceneid'=>$this->sceneid,'ticketid'=>$res['ticket'],'url'=>$res['url'],'nickname'=>$fans['nickname'],'avatar'=>$fans['avatar']),array('id'=>$sid));
			return $res['url'];
		}
		
	}


    private function uploadImage($img) {
		$url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=".$this->getAccessToken()."&type=image";
		$post = array('media' => '@' . $img);
		load()->func('communication');
		$ret = ihttp_request($url, $post);
		$content = @json_decode($ret['content'], true);
		return $content['media_id'];
	}


     public function sendImage($openid, $media_id) {
	    $data = array(
	      "touser"=>$openid,
	      "msgtype"=>"image",
	      "image"=>array("media_id"=>$media_id));
	    $ret = $this->postRes($this->getAccessToken(), json_encode($data));
	    return $ret;
	  }

    private function PostNews($poster,$name){//图文
		$stitle = unserialize($poster['stitle']);
		if (!empty($stitle)){
			$thumbs = unserialize($poster['sthumb']);
			$sdesc = unserialize($poster['sdesc']);
			$surl = unserialize($poster['surl']);
			foreach ($stitle as $key => $value) {
				if (empty($value)) continue;
				$response[] = array(
					'title' => str_replace('#昵称#',$name,$value),
					'description' => $sdesc[$key],
					'picurl' => tomedia( $thumbs[$key] ),
					'url' => $this->buildSiteUrl($surl[$key])
				);
			}
			if ($response) return $this->respNews($response);
		}
		return '';
	}

    


   //客服消息
    public function postText($openid, $text) {
		$post = '{"touser":"' . $openid . '","msgtype":"text","text":{"content":"' . $text . '"}}';
		$ret = $this->postRes($this->getAccessToken(), $post);
		return $ret;
	}

    private function postRes($access_token, $data) {
		$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$access_token}";
		load()->func('communication');
		$ret = ihttp_request($url, $data);
		$content = @json_decode($ret['content'], true);
		return $content['errcode'];
	}

    private function getAccessToken() {
		global $_W;
		load()->model('account');
		$acid = $_W['acid'];
		if (empty($acid)) {
			$acid = $_W['uniacid'];
		}
		$account = WeAccount::create($acid);
		//$token = $account->fetch_available_token();
        $token = $account->getAccessToken();
		return $token;
	}










}